<template>
	<view class="news-container">
		
		<view class="tabs">
			<scroll-view class="tabs-title" scroll-x="true">
				<view
					:class="active===index?'active': ''"
					v-for="(item, index) in tabList"
					:key="index"
					@click="ontabtap(index)"
				>{{ item.name }}</view>
			</scroll-view>
			<Newslist
				v-for="(item, index) in news"
				:key="item.id"
				:article_type="item.article_type"
				:comment_count="item.comment_count"
				:datetime="item.datetime"
				:img_url="item.img_url"
				:source="item.source"
				:title="item.title"
				@click.native="tonewsdetail(item.id)"
			></Newslist>
		</view>
		
	</view>
</template>

<script>
	import { friendlyDate } from '../../common/util.js'
	import newslist from '../../components/newslist.vue'
	
	export default {
		data() {
			return {
				tabList: [
					{
						id: 'tab01',
						name: '推荐'
					},
					{
						id: 'tab02',
						name: '要闻'
					},
					{
						id: 'tab03',
						name: '新思想'
					},
					{
						id: 'tab04',
						name: '广东'
					},
					{
						id: 'tab05',
						name: '综合'
					},
					{
						id: 'tab06',
						name: '科技'
					},
					{
						id: 'tab07',
						name: '军事'
					},
					{
						id: 'tab08',
						name: '体育'
					},
					{
						id: 'tab09',
						name: '文化'
					},
					{
						id: 'tab10',
						name: '旅游'
					},
					{
						id: 'tab11',
						name: '国际'
					}
				],
				active: 0,
				news: []
			}
		},
		methods: {
			requestNewList() {
				uni.request({
					url: 'http://localhost:3000/news',
					method: 'POST',
					data: {
						type: this.active
					},
					success: res => {
						res.data.res.forEach(item => {
							item.datetime = friendlyDate(new Date(item.datetime))
						})
						console.log(res.data.res)
						this.news = res.data.res
					}
				})
			},
			ontabtap(index) {
				this.active = index
				console.log(this.active)
				this.requestNewList()
			},
			tonewsdetail(id) {
				if(this._isWidescreen) {
					uni.$emit('updateDetail', {
						detail: id
					})
				}
				else {
					uni.navigateTo({
						url: `./newsdetail?id=${id}`
					})
				}
			}
		},
		onLoad() {
			let mediaQueryOb = uni.createMediaQueryObserver(this)
			mediaQueryOb.observe({
				minWidth: 768
			}, matches => {
				this._isWidescreen = matches
			})
			if(this._isWidescreen) uni.hideTabBar({})
			this.requestNewList()
		},
		components: {
			Newslist: newslist
		}
	}
</script>

<style lang="scss">
page {
	height: 100%;
}
.news-container {
	height: 100%;
	.tabs {
		height: 100%;
		.tabs-title {
			width: 100%;
			white-space: nowrap;
			view {
				display: inline-block;
				height: 40px;
				width: 60px;
				line-height: 40px;
				color: #333;
				text-align: center;
				border-right: 1px solid #eee;
				border-bottom: 1px solid #eee;
			}
			.active {
				background: #aa0000;
				color: #ffffff;
			}
		}
	}
}
</style>
